package com.browser.bookmark.controller;

import com.browser.bookmark.utils.JWTUtil;
import com.browser.bookmark.utils.RedisUtils;
import com.browser.bookmark.entity.User;
import com.browser.bookmark.service.impl.IMailServiceImpl;
import com.browser.bookmark.utils.Md5Util;
import com.browser.bookmark.utils.RespBean;
import com.browser.bookmark.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @Auther: Wang
 * @Date: 2020/02/08 16:18
 */
@Api(description = "登录 注册接口")
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private IMailServiceImpl mailService;

    private final Long time = 1800L;


    @RequestMapping(value = "/unauth")
    @ResponseBody
    public Object unauth() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "1000000");
        map.put("msg", "登录成功");
        return map;
    }

    @RequestMapping(value = "/errors")
    @ResponseBody
    public Object errors() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "100404");
        map.put("msg", "没有权限");
        return map;
    }

    @ApiOperation(value = "注册功能")
    @RequestMapping("/regist")
    public RespBean regist(@RequestBody User user) {
        //验证码判断
        //缓存验证码
        if (user.getVerification().equals(redisUtils.get(user.getEmail()))) {
            //盐值
            String salt = Integer.toString((int) ((Math.random() * 9 + 1) * 100000));
            user.setPassword(Md5Util.md5(user.getPassword(), user.getUserName() + salt));

            User email = new User();
            email.setEmail(user.getEmail());
            if (iUserService.countByExample(email) != 0) {
                return new RespBean("EMAIL", "邮箱已经被绑定!");
            }
            User username = new User();
            username.setUserName(user.getUserName());
            Long i = iUserService.countByExample(username);
            if (i != 0) {
                //用户名已经存在
                return new RespBean("USERNAME", "用户名已经存在!");
            }
            user.setNickName(user.getUserName());
            user.setSalt(salt);
            user.setFace("https://s2.ax1x.com/2020/03/01/3gV5Tg.jpg");
            user.setLoginIp("127.0.0.1");
            Date datee = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = format.format(datee);
            user.setCreateTime(dateStr);
            user.setSignature("不比别人努力，有什么资格抱怨。");
        } else {
            return new RespBean("emaillErroe", "验证码错误!");
        }
        int i = iUserService.insertSelective(user);
        if (i == 1) {
            return new RespBean("success", "注册成功!");
        }
        return new RespBean("error", "注册失败!");
    }

    @ApiOperation(value = "发送验证码")
    @PostMapping("/emailQQ")
    @ResponseBody
    public RespBean emailQQs(@RequestBody User user) {
        try {
            System.out.println("邮箱是:" + user.getEmail());
            //6位0
            String verification = Integer.toString((int) ((Math.random() * 9 + 1) * 100000));
            mailService.sendSimpleMail(user.getEmail(), "BookMark网", "你的验证码是:" + verification + "请在30分钟内使用");
            //缓存验证码
            redisUtils.set(user.getEmail(), verification, time);
        } catch (Exception ex) {
            ex.printStackTrace();
            return new RespBean("100021", "邮件发送异常失败!");
        }
        return new RespBean("100022", "邮件发送成功,!");
    }


    @ApiOperation(value = "登录")
    @PostMapping("/login")
    @ResponseBody
    public RespBean login(@RequestBody User user) {
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            System.out.println("验证token结果");
            return new RespBean("200", "登录成功");
        }

        User users = iUserService.selectUser(user.getUserName());
        if (users == null) {
            System.out.println("用户名错误");
            return new RespBean("201", "用户名错误");
        }
        if (users != null && users.getPassword().equals(user.getPassword())) {
            return new RespBean("200", "Login success", JWTUtil.sign(user.getUserName(), user.getPassword()));
        } else {
            System.out.println("密码错误");
            return new RespBean("202", "密码错误");
        }
    }

    @ApiOperation(value = "退出登录")
    @RequestMapping("/logout")
    public Object logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "1000005");
        map.put("msg", "退出成功");
        return map;
    }


    @RequestMapping("/notlogin")
    public Object notlogin() {
        SecurityUtils.getSubject().logout();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "1000009");
        map.put("msg", "未授权");
        return map;
    }
}
